package com.surprise.bweb.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.surprise.base.util.JacksonUtils;
import com.surprise.base.util.Md5Utils;
import com.surprise.biz.utils.UserSessionUtils;
import com.surprise.bweb.aspect.UserAuth;
import com.surprise.bweb.bo.EditUploadRes;
import com.surprise.bweb.manager.SessionManager;
import com.surprise.db.entity.BUser;
import com.surprise.ods.aliyun.OSSService;

/**
 * SurpriseEditController.java
 * @author xuling
 * @since 2017年9月28日
 */
@Controller
@RequestMapping(value = "/api", produces = { "application/json" })
public class SurpriseEditController {

	@Autowired
	private OSSService ossService;
	
	@Autowired
	private SessionManager sessionManager;
	
	@RequestMapping("/editor")
	@ResponseBody
	@UserAuth
	public void editorAction(String action, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (action.equals("config")) {
			String data = IOUtils.toString(SurpriseEditController.class.getClassLoader().getResourceAsStream("editor.json"));
			response.getWriter().print(data);
			return;
		} else if (action.equals("uploadimage")) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			BUser user = sessionManager.getCurrentUser();

			for (Map.Entry<String, MultipartFile> entry : multipartRequest.getFileMap().entrySet()) {
				MultipartFile uploadFile = entry.getValue();
				if (!uploadFile.isEmpty()) {
					try {
						byte[] bytes = uploadFile.getBytes();
						String name = Md5Utils.md5(bytes);
						String url = ossService.put(UserSessionUtils.userImageKey(user.getId()), name + ".jpg", bytes);
						response.getWriter().print(JacksonUtils.toJson(new EditUploadRes(url, "SUCCESS")));
						return;
					} catch (Exception e) {
						response.getWriter().print(JacksonUtils.toJson(new EditUploadRes("", "FAIL")));
						return;
					}
				}
				response.getWriter().print(JacksonUtils.toJson(new EditUploadRes("", "FAIL")));
				return;
			}
		}
	}
}
